package com.kun.web.controller.activiti;

import com.kun.service.service.ITaskHistory;
import com.kun.utils.AjaxResult;
import com.kun.utils.SecurityUtils;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/task-history")
public class TaskHistoryController {

    private final HistoryService historyService;
    private final ITaskHistory taskHistory;

    public TaskHistoryController(HistoryService historyService, ITaskHistory taskHistory) {
        this.historyService = historyService;
        this.taskHistory = taskHistory;
    }

    /**
     * 用户历史任务
     */
    @GetMapping("/my-user")
    public ResponseEntity<AjaxResult> getUserTaskHistory() {
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                // 按照最后完成时间排序
                .orderByHistoricTaskInstanceEndTime().desc()
                // 指定待办人
                .taskAssignee(SecurityUtils.getUsername())
                .list();
        return AjaxResult.success(list);
    }

    /**
     * 根据流程实例ID查询任务
     */
    @GetMapping("/process/{processInstanceId}")
    public ResponseEntity<AjaxResult> getTasksByProcessInstanceId(@PathVariable String processInstanceId) {
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                // 按照最后完成时间排序
                .orderByHistoricTaskInstanceEndTime().desc()
                // 根据流程实例ID查询任务
                .processInstanceId(processInstanceId)
                .list();
        return AjaxResult.success(list);
    }

    /**
     * 高亮显示流程历史
     *
     * @param processInstanceId 流程实例ID
     */
    @GetMapping("/highlight/{processInstanceId}")
    public ResponseEntity<AjaxResult> highlightProcessHistory(@NotBlank(message = "流程实例ID不能为空")
                                                              @PathVariable String processInstanceId) {
        return AjaxResult.success(taskHistory.highlightProcessHistory(processInstanceId));
    }

}
